define(['route-config',
    'templates',
    'angularLocale',
    'uiRoute',
    'angularResource',
    'angularCookies',
    'angularSanitize',
    'bootstrapUI',
    'uislider',
    'jqueryFileuploadAngular',
    'treeControl',
    'indexController',
    'js/directives/SlimScroll'
], function (routeConfig) {
    var app = angular.module('app', ['ui.router', 'ngResource', 'ngSanitize', 'ngCookies', 'ui.bootstrap', 'ui.slider', 'blueimp.fileupload', 'FC.App.Templates', 'treeControl', 'SlimScroll']);
    app.run(['$rootScope', function ($rootScope) {
        $rootScope.global_PageSize = 10;
        $rootScope.loadingMsg = '';
        $rootScope.curUserObj = window.curUserObj;
        $rootScope.curOrgObj = window.curOrgObj;
        //列表查询条件保存到session url地址 ，避免查询翻页，编辑页面返回后，查询条件和页面丢失问题
        $rootScope.global_searchCondToSessionUrl = baseServices_restfulUrl + 'SearchCondController/searchCondToSession';
        $rootScope.global_postHeaders = {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'};
        $rootScope.global_getSearchCondFromSessionUrl = baseServices_restfulUrl + 'SearchCondController/getSearchCondFromSession';

        //模块列表页面的进入方式 ，用于列表页面初始化查询数据时，是否从session种获取之前的查询条件和页码
        $rootScope.global_listPage_enterType_menu = 'fromMenu';  //通过左侧菜单
        $rootScope.global_listPage_enterType_return = 'fromReturn'; //通过编辑页面返回
        $rootScope.global_listPage_enterType_locationUrl = 'fromLocationUrl'; //直接从浏览器地址类

        //ui-router跳转，返回保存数据到本地，并通过本地注入时读取
        $rootScope.$on('$stateChangeStart',
            function (event, toState, toParams, fromState, fromParams) {
                app.injectCacheData(event.targetScope, toState);
            })

    }]);
    //登陆超时拦截标志，记录第一次超时时的URL地址(huxiaoyuan 2014/05/27)
    var interFlag = true;
    var oldHref = '';

    app.config(['$controllerProvider',
        '$compileProvider',
        '$filterProvider',
        '$provide',
        '$locationProvider',
        '$stateProvider',
        '$urlRouterProvider',
        function ($controllerProvider, $compileProvider, $filterProvider, $provide, $locationProvider, $stateProvider, $urlRouterProvider) {

            app.lazy = {
                controller: $controllerProvider.register,
                directive: $compileProvider.directive,
                filter: $filterProvider.register,
                factory: $provide.factory,
                service: $provide.service
            };
            $compileProvider.aHrefSanitizationWhitelist(/^\s*(http?|file|tel):/); //跳转其他页面需要。
            if (routeConfig.states !== undefined) {
                angular.forEach(routeConfig.states, function (route, state) {
                    if (route.dependencies !== undefined && route.dependencies.length > 0) {
                        route.resolve = resolve(route.dependencies);
                    }

                    $stateProvider.state(state, route);
                });
            }
            if (routeConfig.defaultUrl !== undefined) {
                $urlRouterProvider.otherwise(routeConfig.defaultUrl);
            }
        }]);


    app.config(['$httpProvider', function ($httpProvider) {

        $httpProvider.defaults.transformRequest = [function (data) {
            return angular.isObject(data) && String(data) !== '[object File]' ? $.param(data) : data;
        }];

        $httpProvider.interceptors.push(['$q', function ($q) {
            return {
                'responseError': function (rejection) {
                    switch (rejection.status) {
                        case 401:
                            /*
                             if(interFlag){
                             oldHref = location.href;
                             var subIndex =  oldHref.indexOf('#');
                             oldHref = oldHref.substring(subIndex+2, oldHref.length);
                             }

                             if(oldHref != ''){
                             location.href = '#/dlogin/'+oldHref;
                             }*/
                            //alert_dialog('警告','您还没有登录 或 太久没操作，服务器断开，请重新登录！','warning');

                            location.href = webPath + '/login.html';
                            interFlag = false;
                            // hideLoading();//隐藏“加载中效果”
                            break;
                        case 500:
                            //location.href = '500.html';
                            // hideLoading();//隐藏“加载中效果”
                            break;
                        case 900://session过期
                            // hideLoading();//隐藏“加载中效果”
                            break;
                        case 901://未登录
                            // hideLoading();//隐藏“加载中效果”
                            break;
                        case 902://无权限
                            location.href = '#/login';
                            // hideLoading();//隐藏“加载中效果”
                            break;
                        default:
                            // hideLoading();//隐藏“加载中效果”
                            break;
                    }
                    return $q.reject(rejection);
                }
            };
        }]);
    }]);

    //显示富文本下带样式html
    app.filter('to_trusted', ['$sce', function ($sce) {
        return function (text) {
            return $sce.trustAsHtml(text);
        };
    }]);

    function resolve (dependencies) {
        return {
            deps: ['$q', function ($q) {
                var deferred = $q.defer();

                require(dependencies, function () {
                    deferred.resolve();
                });

                return deferred.promise;
            }]
        };
    }

    //加载首页控制器
    app.controller('indexController', indexController);

    //---------缓存数据用-------ui-router跳转，返回保存数据到本地，并通过本地注入时读取
    /**
     * 注册保存缓存数据
     * @param $scope
     * @param $state
     */
    app.regsiterCacheData = function ($scope, $state) {
        var stateName = $state.current.name;
        $scope.$on('$destroy', function () {
            //保存来时的状态状态
            var cScrope = $scope;
            var saveData = {
                'queryObj': cScrope.queryObj,
                'pagerObj': cScrope.pagerObj
            }
            var saveName = "data_" + stateName;
            setSessionJson(saveName, saveData);
        });
    };

    /**
     * 注入缓存数据
     * @param $scope
     * @param $state
     */
    app.injectCacheData = function ($scope, $state) {
        var toStateName = $state.name;

        //从数据中读取
        if (!isEmpty(toStateName)) {
            var saveName = "data_" + toStateName;
            var saveData = getSessionJson(saveName);

            var tScope = $scope;
            if (!isEmpty(saveData)) {
                tScope.queryObj = saveData.queryObj;
                tScope.pagerObj = saveData.pagerObj;
            }
        }
    }
    return app;
});
